package com.code2roc.jarmanage.servlet.redis;

import com.code2roc.jarmanage.model.RedisKeyInfo;
import com.code2roc.jarmanage.model.Result;
import com.code2roc.jarmanage.util.*;
import redis.clients.jedis.Jedis;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

public class GetDataBaseKeyListServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        Result result = Result.okResult();
        HashMap params = CommonUtil.getParamMap(req);
        int dbIndex = ConvertUtil.convert2Int(params.get("dbIndex"));
        int pageIndex = ConvertUtil.convert2Int(params.get("pageIndex"));
        int pageSize = ConvertUtil.convert2Int(params.get("pageSize"));
        String pattern = ConvertUtil.convert2String(params.get("pattern"));
        if (StringUtil.isEmpty(pattern)) {
            pattern = "*";
        }
        List<RedisKeyInfo> redisKeyInfoList = new ArrayList<>();
        int total = 0;
        if (dbIndex != -1) {
            Jedis client = JedisUtil.getClient();
            try {
                List<String> keyList = JedisUtil.getKeys(pattern,client, dbIndex,false);
                total = keyList.size();
                keyList = keyList.stream().skip((pageIndex - 1) * pageSize).limit(pageSize).collect(Collectors.toList());
                for (String key : keyList) {
                    String keyType = JedisUtil.getKeyType(client, dbIndex, key,false);
                    long ketExpire = JedisUtil.getKeyExpire(client, dbIndex, key,false);
                    redisKeyInfoList.add(new RedisKeyInfo(key, keyType, ketExpire));
                }
            } catch (Exception e) {
                LogUtil.error(e);
                throw e;
            } finally {
                client.close();
            }
        }
        result.add("rows", redisKeyInfoList);
        result.add("total", total);
        resp.getWriter().println(result.toString());
    }
}
